<?php

namespace App\Http\Controllers\Caiwu;

use App\Http\Controllers\Controller;
use App\Models\Contract;
use App\Models\Customer;
use App\Models\Department;
use App\Models\Finance;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\View;

class ContractController extends Controller
{
    /**
     * 合同列表
     * @param Request $request
     * @return \Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse
     */
    public function index(Request $request)
    {
        if ($request->ajax()){
            $user = $request->user();
            $data = $request->all([
                'customer_id',
                'num',
            ]);
            $res = Contract::query()
                ->with('customer')
                ->where(function ($query) use ($user) {
                    if ($user->hasPermissionTo('caiwu.contract.list_all')) {
                        return $query->where('owner_user_id', '>', 0);
                    } elseif ($user->hasPermissionTo('caiwu.contract.list_department_sub')) {
                        $departmentIds = Department::query()->where('parent_id',$user->department_id)->pluck('id')->toArray();
                        $departmentIds = array_merge($departmentIds,[$user->department_id]);
                        return $query->whereIn('owner_department_id', $departmentIds);
                    } elseif ($user->hasPermissionTo('caiwu.contract.list_department')) {
                        return $query->where('owner_department_id', '=', $user->department_id);
                    } else {
                        return $query->where('owner_user_id', $user->id);
                    }
                })
                ->when($data['customer_id'], function ($query) use ($data) {
                    return $query->where('customer_id', $data['customer_id']);
                })
                ->when($data['num'], function ($query) use ($data) {
                    return $query->where('num', $data['num']);
                })
                ->orderByDesc('id')
                ->paginate($request->get('limit', 30));
            return $this->success('ok', $res->items(), $res->total());
        }
        return View::make('caiwu.contract.index');
    }

    public function create()
    {
        return View::make('caiwu.contract.create');
    }

    public function store(Request $request)
    {
        $data = $request->all([
            'customer_id',
            'stime',
            'etime',
            'total_money',
            'payed_money',
            'multiple_file',
            'remark',
        ]);
        $customer = Customer::query()->where('id',$data['customer_id'])->first();
        if ($customer == null){
            return $this->error('请选择客户');
        }
        try {
            $data = array_merge($data,[
                'num' => create_num('ht'),
                'owner_department_id' => $request->user()->department_id,
                'owner_user_id' => $request->user()->id,
                'owner_user_nickname' => $request->user()->nickname,
            ]);
            Contract::create($data);
            return $this->success('操作成功，请等待管理员审核');
        }catch (\Exception $exception){
            Log::error('生成合同异常:'.$exception->getMessage());
            return $this->error();
        }
    }

    public function edit(Request $request,$id)
    {
        $model = Contract::query()->with('customer')->find($id);
        return View::make('caiwu.contract.edit',compact('model'));
    }

    public function update(Request $request,$id)
    {
        $model = Contract::query()->with('customer')->find($id);
        $data = $request->all([
            'stime',
            'etime',
            'total_money',
            'payed_money',
            'multiple_file',
            'remark',
        ]);
        try {
            // 更新后合同需要重新审核，不论数据是否有变动
            $data = array_merge($data,[
                'check_status' => 1,
                'check_result' => null,
                'check_time' => null,
                'check_user_id' => 0,
                'check_user_nickname' => null,
            ]);
            $model->update($data);
            return $this->success('操作成功，请等待管理员审核');
        }catch (\Exception $exception){
            Log::error('更新合同异常:'.$exception->getMessage());
            return $this->error();
        }
    }

    /**
     * 删除合同
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function destroy(Request $request)
    {
        $ids = $request->input('ids');
        try {
            Contract::query()->whereIn('id', $ids)->delete();
            return $this->success();
        } catch (\Exception $exception) {
            Log::error('删除合同异常：' . $exception->getMessage());
            return $this->error();
        }
    }

    /**
     * 审核合同
     * @param Request $request
     * @return \Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse
     */
    public function check(Request $request)
    {
        $model = Contract::query()->find($request->input('id'));
        if ($request->ajax()){
            try {
                $data = $request->all(['check_status','check_result']);
                if ($data['check_status']==null){
                    return $this->error('请选择状态');
                }
                $data = array_merge($data,[
                    'check_time' => date('Y-m-d H:i:s'),
                    'check_user_id' => $request->user()->id,
                    'check_user_nickname' => $request->user()->nickname,
                ]);
                $model->update($data);
                return $this->success();
            }catch (\Exception $exception){
                Log::error('审核合同异常：'.$exception->getMessage());
                return $this->error();
            }
        }
        return View::make('caiwu.contract.check',compact('model'));
    }

}
